from fusionmatrix.utils import Config
from PySide6.QtWidgets import QWidget, QDialog, QLabel, QLineEdit, QTextBrowser, QPushButton
from PySide6.QtWidgets import QVBoxLayout, QGridLayout
from PySide6.QtGui import Qt
from PySide6.QtCore import QTimer

from typing import Optional


class ModelConfigDialog(QDialog):

    def __init__(self, parent: Optional[QWidget] = None) -> None:
        super().__init__(parent)

        self.setWindowTitle("模型管理")
        self.setMinimumWidth(350)

        self.api_key_label = QLabel("模型服务令牌")
        self.api_key_input = QLineEdit()
        self.api_base_label = QLabel("模型服务地址")
        self.api_base_input = QLineEdit()
        self.model_name_label = QLabel("使用模型名称")
        self.model_name_input = QLineEdit()
        self.btn_confirm = QPushButton("确认")
        self.btn_cancel = QPushButton("取消")
        self.btn_confirm.clicked.connect(self.accept)
        self.btn_cancel.clicked.connect(self.reject)

        self.config = Config.load_default_config()
        self.api_key_input.setText(self.config.chat_model.api_key)
        self.api_base_input.setText(self.config.chat_model.api_base)
        self.model_name_input.setText(self.config.chat_model.api_model_name)

        layout = QGridLayout()
        layout.addWidget(self.api_base_label, 0, 0, Qt.AlignmentFlag.AlignRight)
        layout.addWidget(self.api_base_input, 0, 1, 1, 2)
        layout.addWidget(self.api_key_label, 1, 0, Qt.AlignmentFlag.AlignRight)
        layout.addWidget(self.api_key_input, 1, 1, 1, 2)
        layout.addWidget(self.model_name_label, 2, 0, Qt.AlignmentFlag.AlignRight)
        layout.addWidget(self.model_name_input, 2, 1, 1, 2)
        layout.addWidget(self.btn_confirm, 3, 1)
        layout.addWidget(self.btn_cancel, 3, 2)

        self.setLayout(layout)
        self.setModal(True)

    def accept(self):
        self.config.chat_model.api_model_name = self.model_name_input.text()
        self.config.chat_model.api_base = self.api_base_input.text()
        self.config.chat_model.api_key = self.api_key_input.text()
        self.config.save_default_config()
        super().accept()


class DebugTerminalDialog(QDialog):

    def __init__(self, parent: Optional[QWidget] = None):
        super().__init__(parent)
        self.console = QTextBrowser(self)
        self.console.setReadOnly(True)
        self.timer = QTimer()
        self.timer.setInterval(500)
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.updateConsole)

        layout = QVBoxLayout()
        self.setLayout(layout)

    def updateConsole(self) -> None:
        pass

    def showEvent(self, _) -> None:
        self.timer.start()

    def hideEvent(self, _) -> None:
        self.timer.stop()
